package com.deekian.weixin.confirm.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.util.Map;

public class SimpleOkHttpUtils {
    public static Result doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }

    public static Result doGet(String url, Map<String, String> params, Map<String, String> headers) {
        StringBuilder param = new StringBuilder();
        if (params != null) {
            params.forEach((k, v) -> param.append("&").append(k).append("=").append(v));
            if (param.length() > 0) {
                param.deleteCharAt(0);
            }
        }
        return doGet(url, param.toString(), headers);
    }

    public static Result doGet(String url, String param, Map<String, String> headers) {
        if (param != null && param.length() > 0) {
            if (url.contains("?")) {
                url += "&" + param;
            } else {
                url += "?" + param;
            }
        }

        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .get();
        return doRequest(requestBuilder, headers);
    }

    private static Result doRequest(Request.Builder builder, Map<String, String> headers) {
        OkHttpClient okHttpClient = new OkHttpClient();
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        Request request = builder.build();
        Result result = new Result();
        try {
            Response response = okHttpClient.newCall(request).execute();
            result.status = response.code();
            result.normal = true;
            try (ResponseBody responseBody = response.body()) {
                if (responseBody != null) {
                    result.result = responseBody.string();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static class Result {
        public int status;
        public boolean normal;
        public String result;

        @Override
        public String toString() {
            return "Result{" +
                    "status=" + status +
                    ", result='" + result + '\'' +
                    '}';
        }
    }
}
